<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <el-input
          v-model="query.processDefinitionName"
          clearable
          size="small"
          placeholder="流程定义名称"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-input
          v-model="query.startedBy"
          clearable
          size="small"
          placeholder="启动人"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <rrOperation />
      </div>
      <crudOperation>
        <template slot="left">
          <el-button
            v-permission="['admin', 'instance:edit']"
            :disabled="!selectIndex"
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-upload"
            @click="crud.toEdit(currentRow)"
          >查看
          </el-button>
        </template>
      </crudOperation>
    </div>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      style="width: 100%"
      @selection-change="handleCurrentChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="流程实例ID" />
      <el-table-column prop="processDefinitionName" label="流程定义名称" />
      <el-table-column prop="processDefinitionKey" label="流程定义KEY" />
      <el-table-column prop="processDefinitionVersion" label="版本" />
      <el-table-column prop="startTime" label="开始时间">
        <template slot-scope="scope">
          <span>{{ scope.row.startTime }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间">
        <template slot-scope="scope">
          <span>{{ scope.row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-permission="['admin', 'instance:edit', 'instance:del']"
        label="操作"
        width="200px"
        align="center"
      >
        <template slot-scope="scope">
          <el-button
            v-permission="['admin', 'instance:edit']"
            style="margin-left: 3px"
            type="text"
            size="mini"
            @click="info(scope.row.id)"
          >详情
          </el-button>
          <el-button
            v-permission="['admin', 'task:list']"
            style="margin-left: 3px"
            type="text"
            size="mini"
            @click="task(scope.row.id)"
          >任务
          </el-button>
          <el-popover
            :ref="'instance' + scope.row.id"
            v-permission="['admin', 'instance:del']"
            placement="top"
            width="180"
          >
            <p>确定删除本条数据吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button
                size="mini"
                type="text"
                @click="$refs['instance' + scope.row.id].doClose()"
              >取消</el-button>
              <el-button
                :loading="delLoading"
                type="primary"
                size="mini"
                @click="delMethod(scope.row.id)"
              >确定</el-button>
            </div>
            <el-button slot="reference" type="text" size="mini">删除</el-button>
          </el-popover>
          <el-popover
            :ref="'history' + scope.row.id"
            v-permission="['admin', 'instance:del']"
            placement="top"
            width="180"
          >
            <p>确定删除本条数据吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button
                size="mini"
                type="text"
                @click="$refs['history' + scope.row.id].doClose()"
              >取消</el-button>
              <el-button
                :loading="delLoading"
                type="primary"
                size="mini"
                @click="delMethod(scope.row.id, true)"
              >确定</el-button>
            </div>
            <el-button
              slot="reference"
              type="text"
              size="mini"
            >删除历史</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
    <!--表单组件-->
    <el-dialog
      append-to-body
      :loading="loading"
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="crud.status.title"
      width="800px"
    >
      <el-form
        ref="form"
        :inline="true"
        :model="form"
        size="small"
        label-width="100px"
        disabled
      >
        <el-form-item label="流程实例ID" prop="id">
          <el-input v-model="form.id" style="width: 220px" />
        </el-form-item>
        <el-form-item label="业务主键Key" prop="businessKey">
          <el-input v-model="form.businessKey" style="width: 220px" />
        </el-form-item>
        <el-form-item label="流程定义ID" prop="processDefinitionId">
          <el-input v-model="form.processDefinitionId" style="width: 220px" />
        </el-form-item>
        <el-form-item label="流程定义名称" prop="processDefinitionName">
          <el-input v-model="form.processDefinitionName" style="width: 220px" />
        </el-form-item>
        <el-form-item label="流程定义KEY" prop="processDefinitionKey">
          <el-input v-model="form.processDefinitionKey" style="width: 220px" />
        </el-form-item>
        <el-form-item label="流程定义版本" prop="processDefinitionVersion">
          <el-input
            v-model="form.processDefinitionVersion"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="启动人ID" prop="startUserId">
          <el-input v-model="form.startUserId" style="width: 220px" />
        </el-form-item>
        <el-form-item label="耗时(毫秒)" prop="durationInMillis">
          <el-input v-model="form.durationInMillis" style="width: 220px" />
        </el-form-item>
        <el-form-item label="子流程ID" prop="superProcessInstanceId">
          <el-input
            v-model="form.superProcessInstanceId"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="状态" prop="suspended">
          <el-input
            v-if="form.endTime == null"
            v-model="form.suspended ? '挂起' : '激活'"
            style="width: 220px"
          />
          <el-input v-else value="结束" style="width: 220px" />
        </el-form-item>
        <el-form-item label="删除原因" prop="reason">
          <el-input v-model="form.reason" style="width: 220px" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button
          v-if="form.endTime == null"
          v-permission="['admin', 'instance:edit']"
          :loading="submitLoading"
          type="primary"
          @click="doSubmit(form, form.suspended)"
        >{{ form.suspended ? '激活' : '挂起' }}</el-button>
      </div>
    </el-dialog>
    <!-- 实例详情 -->
    <process-detail
      v-if="dialogInfoVisible"
      :visible.sync="dialogInfoVisible"
      :process-instance-id="processInstanceId"
    />
  </div>
</template>

<script>
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import processDetail from '../components/ProcessDetail'
import crudInstance from '@/api/flowable/instance'

const defaultForm = {}
export default {
  name: 'FlowableProcessInstance',
  components: { processDetail, pagination, crudOperation, rrOperation },
  cruds() {
    return CRUD({ title: '流程实例', url: 'api/flowable/instance', crudMethod: { ...crudInstance }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      loading: false,
      submitLoading: false,
      delLoading: false,
      dialogInfoVisible: false,
      processInstanceId: '',
      currentRow: null,
      selectIndex: '',
      form: {},
      permission: {
        add: ['admin', 'instance:add'],
        edit: ['admin', 'instance:edit'],
        del: ['admin', 'instance:del']
      }
    }
  },
  created() {
    this.crud.optShow = {
      add: false,
      edit: false,
      del: false,
      download: false
    }
  },
  methods: {
    // 编辑前
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.loading = true
      crudInstance.getDetail(form.id).then(res => {
        this.form = res
        this.loading = false
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    // 详情
    info(processInstanceId) {
      this.processInstanceId = processInstanceId
      this.dialogInfoVisible = true
    },
    // 任务
    task(row) {
      this.$router.push({ path: '/workflow/flowable/task', query: { processInstanceId: row.id }})
    },
    delMethod(id, cascade) {
      this.delLoading = true
      crudInstance.del(id, cascade).then(() => {
        this.delLoading = false
        this.$refs[(cascade === undefined ? 'instance' : 'history') + id].doClose()
        this.crud.dleChangePage(1)
        this.crud.delSuccessNotify()
        this.crud.toQuery()
      }).catch(() => {
        this.delLoading = false
        this.$refs[(cascade === undefined ? 'instance' : 'history') + id].doClose()
      })
    },
    cancel() {
      this.dialog = false
    },
    doSubmit(row, suspend) {
      this.submitLoading = true
      if (suspend) {
        crudInstance.activate(row.id).then(res => {
          this.submitLoading = false
          this.form.suspended = !suspend
          this.crud.notify('激活成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(err => {
          console.log(err.response.data.message)
        })
      } else {
        crudInstance.suspend(row.id).then(res => {
          this.submitLoading = false
          this.form.suspended = !suspend
          this.crud.notify('挂起成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(err => {
          console.log(err.response.data.message)
        })
      }
    },
    handleCurrentChange(selection) {
      this.crud.selections = selection
      if (selection.length === 1) {
        const row = selection[0]
        this.selectIndex = row.id
        this.currentRow = row
        this.times = this.times + 1
        this.processDefinitionId = row.id
        this.processDefinitionName = row.name
      } else {
        this.currentRow = {}
        this.selectIndex = ''
      }
    }
  }
}
</script>
